import 'package:app_30/util/other_utils.dart';
import 'package:flutter/material.dart';

class NavigatorManger {
  String? cruStack = null;

  List<String> _activityStack = <String>[];

  NavigatorManger._internal();

  static NavigatorManger singleton = new NavigatorManger._internal();

  //工厂模式
  factory NavigatorManger() => singleton;

  //添加唯一标识到数组中
  void addWidget(BuildContext context) {
    print("BaseWidget__" + context.toString());
    _activityStack.add(getClassName(context).nullSafe);
  }

  //移除唯一标识
  void removeWidget(BuildContext context) {
    _activityStack.remove(cruStack.nullSafe);
  }

  //通过上下文获取page唯一标识
  String? getClassName(BuildContext _buildContext) {
    if (_buildContext == null) {
      return null;
    }
    String className = _buildContext.toString();
    if (className == null) {
      return null;
    }
    className = className.substring(0, className.indexOf("(")).toString();
    print('唯一标识:${className}');
    return className;
  }

  //通过数组中标识队列，判断page的位置（是唯一最顶部，还是唯一最顶部之下的第二个page）
  bool isTop(BuildContext context, int num) {
    if (_activityStack == null) {
      return false;
    }
    try {
      cruStack = getClassName(context);
      int stackLength = _activityStack.length;
      int curIndex = (stackLength >= num) ? (stackLength - num) : -1;
      String? stackClassName = curIndex >= 0 ? _activityStack[curIndex] : null;
      return (stackClassName == null) ? false : (stackClassName == cruStack);
    } catch (exception) {
      return false;
    }
  }

  bool isTopPage(BuildContext context) {
    return isTop(context, 1);
  }

  bool isSecondTop(BuildContext context) {
    return isTop(context, 2);
  }
}
